package main

import (
	"crypto/md5"
	"fmt"
)

type AppInfo struct {
	AppID             string            `json:"login_name"`
	PasswdShadow      string            `json:"passwd_shadow"`
	AllowedContainers []string          `json:"docker_id"`
	TrustedClientKeys map[string]string `json:"trusted_client_keys"` //无参数
}

func (a *AppInfo) Auth(passwd string) bool { // (a *AppInfo)表示a可使用此方法
	md5sum := md5.Sum([]byte(passwd))
	return fmt.Sprintf("%x", md5sum) == a.PasswdShadow
}

func (a *AppInfo) AuthContainer(cid string) bool {
	for _, id := range a.AllowedContainers {
		if cid == id {
			return true
		}
	}
	return false
}

func ParseCommandAndCid(appid string, input []string) (output []string, cid string) { //解析ssh命令行  并转换成宿主机的命令行
	if len(input) < 1 {
		return
	}
	if input[0] == "reg" { //公钥
		output = []string{"reg"}
		return
	}
	if input[0] == "bash" {
		output = []string{"sudo", "-u", appid, "bash"}
		return
	}
	if input[0] == "ps" {
		output = append([]string{"docker"}, input...)
		return
	}
	if len(input) == 2 {
		if cmd := input[0]; cmd == "start" || cmd == "stop" || cmd == "restart" || cmd == "stats" {
			output = append([]string{"docker"}, input...)
			cid = input[1]
		} else if cmd == "exec" {
			cid = input[1]
			output = append([]string{"docker"}, cmd, "-it", input[1], "bash")
		}

	}
	if input[0] == "logs" {
		if len(input) == 2 {
			cid = input[1]
			output = append([]string{"docker"}, input...)
			return
		} else if len(input) == 3 && input[2] == "-f" {
			cid = input[2]
			output = append([]string{"docker"}, input...)
			return
		}
	}
	if input[0] == "rm" {
		if len(input) == 2 {
			cid = input[1]
			output = append([]string{"docker"}, input...)
			return
		} else if len(input) == 3 && input[2] == "-f" {
			cid = input[2]
			output = append([]string{"docker"}, input...)
			return
		}
	}
	return
}
